﻿using Consul;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure
{
    public class ServiceUrL
    {
        public static int number = 1;
        //通过调用Consul查询对应的服务地址，方便gRPC调用
        public static string GetServiceUrlByName(string name)
        {
            var consulClient = new ConsulClient(x => x.Address = new Uri($"http://localhost:8500"));
            var agent = consulClient.Agent.Services().Result.Response.Values.ToList();
            var services = agent.Where(c => c.Service == name).ToList();
            if (services != null)
            {
                var index = number++ % services.Count;
                var result = services[index];
                return string.Format("https://{0}:{1}", result.Address, result.Port);
            }
            else
            {
                throw new Exception("没有找到地址");
            }
        }
    }
}
